package com.ics.cmsadmin.frame.utils;

import org.apache.commons.collections4.MapUtils;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.StringWriter;
import java.util.Map;
import java.util.Properties;

public final class VelocityUtils {

    static {
        Properties p = new Properties();
        p.put("file.resource.loader.class",
            "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(p);
    }

    /**
     * 获取 Velocity Content
     * @param vmPath vm路径
     */
    public static String getContent(String vmPath){
        return getContent(vmPath, null);
    }

    /**
     * 获取 Velocity Content
     * @param vmPath vm路径
     * @param params 参数
     */
    public static String getContent(String vmPath, Map<String, Object> params){
        VelocityContext velocityContext = new VelocityContext();
        if (MapUtils.isNotEmpty(params)){
            for (Map.Entry<String, Object> entry : params.entrySet()){
                velocityContext.put(entry.getKey(), entry.getValue());
            }
        }
        StringWriter sw = new StringWriter();
        Template template = Velocity.getTemplate(vmPath, "utf-8");
        template.merge(velocityContext, sw);
        return sw.toString();
    }
}
